/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package resultEditor.relationship.attributes;


import java.awt.Component;
import java.awt.Dimension;
import java.util.ArrayList;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumn;
import resultEditor.annotations.Annotation;
import resultEditor.annotations.AnnotationAttributeDef;
import resultEditor.annotations.AnnotationRelationship;
import userInterface.GUI;

/**
 *
 * @author Chris Leng 2012
 */
public class Editor extends javax.swing.JFrame {

    private Annotation annotation;
    private AnnotationRelationship relationship;
    private Component caller; 
    private userInterface.GUI GUI;
            
    /**
     * Creates new form Editor
     */
    public Editor(Annotation annotation, AnnotationRelationship relationship, userInterface.GUI GUI, Component caller) {
        initComponents();
        this.caller = caller;
        this.annotation = annotation;
        this.relationship = relationship;
        this.GUI = GUI;
        
        // set window size and location
        this.setPreferredSize( new Dimension(757, 502));
        this.setLocationRelativeTo( GUI );
        
        // list attributes
        listAttributes();
        
        this.delete.setEnabled( false );
    }

    
    /**list the attributes of relationship on the table*/
    private void listAttributes(){
        //Build the model
        TableModel tableModel = buildModel();
        
        //If the table model is non null then use it.
        if (tableModel != null)
        {
            this.jTable1.setModel(tableModel);
            setTableAttributes();
        }

        // imply table for its changes
        ((DefaultTableModel) jTable1.getModel()).fireTableDataChanged();
        
    }
    
    
    /**
     * Set up the table properties
     */
    private void setTableAttributes()
    {        
        //Set row height and margin
        jTable1.setRowHeight(24);
        jTable1.setRowMargin(2);
        
        //Set the renderers and cell editors for each column
        for(int i = 0; i< jTable1.getColumnCount(); i++)
        {
            TableColumn column = jTable1.getColumnModel().getColumn(i);
            //Set the cell renderer
            CellRenderer renderer = new CellRenderer();
            column.setCellRenderer(renderer);
            //Set the cell editor
            TableCellEditor editor = new PropertyCellEditor(this);
            column.setCellEditor(editor);
        }
        

    }
    
    /**empty the jlist component*/
    private void clearList()
    {
        ((DefaultTableModel) jTable1.getModel()).getDataVector().removeAllElements();
        ((DefaultTableModel) jTable1.getModel()).fireTableDataChanged();
    }
    
    /**
     * Build the table model with all of the entries that were passed in to our editor.
     * @return
     */
    private TableModel buildModel()
    {
        // empty the jList
        clearList();

        //Create a new PropertyTableModel
        TableModel tablemodel = new TableModel( 
                // attributes that this relationship already had.
                this.relationship.attributes,
                // schema attributes
                env.Parameters.RelationshipSchemas.getRelationshipSchema( this.relationship.getMentionSlotID() )
                ); // Vector<AnnotationAttributeDef> attributes, RelationshipDef relationshipSchema
        


        //Empty out the Property Table Model
        //tablemodel.removeAllRows();

        
        
        
        
        
            
        
        //return
        return tablemodel;

    }
    
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel5 = new javax.swing.JPanel();
        delete = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Relationship Attributes Editor ");

        jPanel1.setBackground(new java.awt.Color(230, 230, 230));
        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(230, 230, 230), 4));
        jPanel1.setLayout(new java.awt.BorderLayout());

        jPanel4.setBackground(new java.awt.Color(230, 230, 230));
        jPanel4.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 51, 153)));
        jPanel4.setLayout(new java.awt.BorderLayout());

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "Attribute", "Value"
            }
        ));
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jTable1MouseReleased(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jPanel4.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jPanel5.setBackground(new java.awt.Color(230, 230, 230));
        jPanel5.setLayout(new java.awt.GridLayout());

        delete.setBackground(new java.awt.Color(230, 230, 230));
        delete.setText("Delete");
        delete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteActionPerformed(evt);
            }
        });
        jPanel5.add(delete);

        jPanel4.add(jPanel5, java.awt.BorderLayout.PAGE_END);

        jPanel1.add(jPanel4, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        jPanel2.setBackground(new java.awt.Color(230, 230, 230));

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/links.jpeg"))); // NOI18N
        jLabel1.setText("Modify attributes on the relationship for current annotation:");

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .add(jLabel1)
                .addContainerGap(686, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .add(jLabel1)
                .addContainerGap(13, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel2, java.awt.BorderLayout.NORTH);

        jPanel3.setBackground(new java.awt.Color(230, 230, 230));

        jButton1.setText("Close");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel3Layout.createSequentialGroup()
                .add(0, 1009, Short.MAX_VALUE)
                .add(jButton1))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap(135, Short.MAX_VALUE)
                .add(jButton1))
        );

        getContentPane().add(jPanel3, java.awt.BorderLayout.SOUTH);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        
        saveChanges();
        
        if( caller instanceof userInterface.GUI ){
            ((userInterface.GUI)caller).setEnabled( true );
            ((userInterface.GUI)caller).display_editor_ListRelationships( this.annotation );
            
        }
        
        if( caller instanceof userInterface.GUI ){
            ((userInterface.GUI)caller).setEnabled( true );
            ((userInterface.GUI)caller).display_editor_ListRelationships( this.annotation );
            
        }
        
        if( caller instanceof userInterface.annotationCompare.Comparator ){
            ((userInterface.annotationCompare.Comparator)caller).setEnabled( true );
            ((userInterface.annotationCompare.Comparator)caller).display_listAttributes( this.annotation );
        }
        
        
        
        this.dispose();
        
        
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jTable1MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseReleased
        if(this.jTable1.getSelectedRow() == -1 )
            delete.setEnabled( false );
        else
            delete.setEnabled( true );
    }//GEN-LAST:event_jTable1MouseReleased

    private void deleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteActionPerformed
        // delete an attribute and it's value
        int selectedrow = this.jTable1.getSelectedRow();
        if( selectedrow==-1)
            return;
        TableModel model = (TableModel) jTable1.getModel();
        
        Row deletedAtt = model.getRowData_inFormatOf_STableData(selectedrow);
        String name = deletedAtt.attributename;
        model.deleteRow(selectedrow);
        
        ((DefaultTableModel)jTable1.getModel()).fireTableDataChanged();   
        
        for( AnnotationAttributeDef att : this.relationship.attributes ){            
                if( att.name.compareTo( name ) == 0 ){
                    att.value = null;
                    
                }
            }
                        
    }//GEN-LAST:event_deleteActionPerformed

    
    private void saveChanges(){
        TableModel model = (TableModel) jTable1.getModel();
        ArrayList<Row> data = model.getData();
        
        
        for( Row modifiedAtt : data ){
            if( modifiedAtt == null )
                continue;
            boolean existing = false;
            for( AnnotationAttributeDef att : this.relationship.attributes ){            
                if( att.name.compareTo( modifiedAtt.attributename ) == 0 ){
                    att.value = modifiedAtt.currentValue;
                    existing = true;
                }
            }
            
            if( existing == false ){
                AnnotationAttributeDef e = new AnnotationAttributeDef();
                e.name = modifiedAtt.attributename;
                e.value = modifiedAtt.currentValue;
                this.relationship.attributes.add(e);
            }
        }
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton delete;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
}
